package com.xujie.application.weather.collectRecords.service;

import com.xujie.common.exceptions.weather.PullDataException;
import com.xujie.common.utils.DateUtils;
import com.xujie.infra.entity.WeatherRecords;
import com.xujie.infra.mapper.WeatherRecordsMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Xujie
 * @since 2024/12/21 00:48
 **/
@Slf4j
@Service
public class JsoupService {
	/**
	 * 网页地址
	 */
	@Value("${weather.pull.url}")
	private String url;

	@Value("${weather.pull.timeOut}")
	private Integer timeOut;

	@Resource
	private WeatherRecordsMapper weatherRecordsMapper;

	/**
	 * 解析网页获取天气数据
	 */
	public void getWeather() {
		if(url == null){
			throw PullDataException.INSTANCE;
		}
		try {
			Document document = Jsoup.parse(new URL(url), timeOut);  //url 最长解析时间
			Elements select = document.select("#hour-wrapper > div.scroller > ul");
			select = select.select("li");
			List<WeatherRecords> weatherRecords = new ArrayList<>();
			AtomicInteger cnt = new AtomicInteger();
			select.forEach(node -> {
				String text = node.text();
				if(text.contains("日")){
					String[] split = text.split("日");
					text = split[1];
					cnt.getAndIncrement();
				}
				String[] split = text.split(" ");
				if(split.length != 4){
					throw PullDataException.INSTANCE;
				}
				if(StringUtils.compare(split[2],"无降水") == 0){
					split[2] = "0";
				}
				WeatherRecords record = WeatherRecords.builder()
								.city("成都")
								.dataDate(DateUtils.today(cnt.get(),split[0]))
								.temperature(Double.parseDouble(split[1].replaceAll("℃", "")))
								.precipitation(Double.parseDouble(split[2].replaceAll("mm", "")))
								.windSpeed(Double.parseDouble(split[3].replaceAll("m/s", "")))
								.build();
				weatherRecords.add(record);
			});
			weatherRecordsMapper.batchInsert(weatherRecords);
			if(log.isDebugEnabled()){
				log.debug("weatherRecords:{}", Arrays.toString(weatherRecords.toArray()));
			}
		} catch (Exception e) {
			throw PullDataException.INSTANCE;
		}
	}
}
